﻿#include "./Main_Ui/MainUi.h"
#include "imgui.h"
#include "imgui_impl_dx11.h"
#include "imgui_impl_win32.h"
#include <d3d11.h>
#include <MinHook.h>
#include <thread>
#include <Windows.h>
#include <optional>
#include "./imgui_d11/msyh.h"
#include <string_view>
#include "dll_main.h"
#include "imgui.h"
#include <string>
#include <vector>
#include "../function/movement/movement.h"
#include "../function/ESP/vision.h"
#include "../function/aimbot/aimbot.h"
#include "function/PlayerData/PlayerData.h"
#include <wincodec.h>
#include "img/texture.h"
#include "function/CGameEvent/CGameEvent.h"
#include "function/Base.h"
#pragma comment(lib, "windowscodecs.lib")
#pragma comment(lib, "d3d11.lib")
#include "../function/CGameEvent/CGameEvent.h"
#include "function/messagebox/messagebox.h"

// 新增头文件
#include <mutex>
#include <unordered_set>
#include <atomic>
#include "function/vish/vs.h"
#include "function/Speech/Speech.h"
#include "function/target_bot/target_bot.h"
#include "function/KEY/KEY.h"
#include "function/Weapon_RCS/Weapon_RCS.h"
#include "function/interfaces/interfaces.cpp"

// ==================== 全局变量声明 ====================
ID3D11Device* g_pd3dDevice = nullptr;
static IDXGISwapChain* g_pSwapChain = nullptr;
static ID3D11DeviceContext* g_pd3dContext = nullptr;
static ID3D11RenderTargetView* view = nullptr;
static HWND g_hwnd = nullptr;
void* origin_present = nullptr;
HMODULE g_hThisDll = nullptr;
std::vector<ID3D11ShaderResourceView*> g_textures;
using Present = HRESULT(__stdcall*)(IDXGISwapChain*, UINT, UINT);

static std::atomic<bool> g_dataThreadRunning{ false };
static std::atomic<bool> g_hookThreadRunning{ false };  // 新增Hook线程状态
static std::atomic<bool> g_aimbothookThreadRunning{ false };  // 新增Hook线程状态
static HANDLE g_hDataThread = nullptr;
static HANDLE g_hHookThread = nullptr;  // 新增Hook线程句柄
static HANDLE g_haimbotHookThread = nullptr;  // 新增Hook线程句柄

ImFont* font = nullptr;
ImFont* font_E = nullptr;
WNDPROC origin_wndProc;

// 全局控制变量
static HANDLE g_hMainThread = nullptr;
static HANDLE g_hUnloadThread = nullptr;

// ==================== 新增优化变量 ====================

// 1. MinHook状态跟踪系统
static std::unordered_set<void*> g_hookedFunctions;
static CRITICAL_SECTION g_hookCriticalSection;

// 2. 资源跟踪系统
struct TrackedResource {
    void* resource;
    std::string type;
    std::string description;
};
static std::vector<TrackedResource> g_trackedResources;
static CRITICAL_SECTION g_resourceCriticalSection;

// 3. 线程同步和状态管理
static std::atomic<bool> g_moduleInitialized{ false };
static std::atomic<bool> g_shutdownRequested{ false };

// ==================== 函数声明 ====================
extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND, UINT, WPARAM, LPARAM);
LRESULT __stdcall WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
DWORD WINAPI SafeUnloadThread(LPVOID lpParam);
long __stdcall my_present(IDXGISwapChain* _this, UINT a, UINT b);
DWORD WINAPI DataUpdateThread(LPVOID lpParam);
DWORD WINAPI HookThread(LPVOID lpParam);
DWORD WINAPI aimbotHookThread(LPVOID lpParam);
static void* CreateInterface(const char* moduleName, const char* interfaceName);
DWORD create(void*);
void SetUp();
BOOL InitializeModule(HMODULE hModule);
void ShutdownModule();
bool InstallHook(void* target, void* detour, void** original);
void TrackResource(void* resource, const std::string& type, const std::string& description = "");
void ReleaseTrackedResources(const std::string& type);

// ==================== 函数实现 ====================

// Hook线程函数 - 执行原本在CreateMove中的功能
DWORD WINAPI HookThread(LPVOID lpParam) {
    while (g_hookThreadRunning) {
        SetUp();
        Bhop();
        ToggleThirdPerson();
        Speech::Speech_Run();
        CheckToggleState(all_settings::aimbot_anitaimbot::aimbot::open_aimbot);
        CheckToggleState(all_settings::aimbot_anitaimbot::Target_Bot::target_bot);
        CheckToggleState(all_settings::visual::local::self::ThirdPerson);
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
    return 0;
}
DWORD WINAPI aimbotHookThread(LPVOID lpParam) {
    while (g_aimbothookThreadRunning) {
        Weapon_RCS();
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
    return 0;
}

// 窗口过程函数 - 保持不变
LRESULT __stdcall WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    WPARAM menu_kjj = all_settings::skin::menu_steeing::menu_kjj;
    if (Menu::menu_open) {
        if (ImGui_ImplWin32_WndProcHandler(hwnd, uMsg, wParam, lParam)) {
            return 1;
        }
        switch (uMsg) {
        case WM_MOUSEMOVE:
        case WM_LBUTTONDOWN:
        case WM_LBUTTONUP:
        case WM_RBUTTONDOWN:
        case WM_RBUTTONUP:
        case WM_KEYDOWN:
        case WM_KEYUP:
        case WM_CHAR:
        case WM_MBUTTONDOWN:
        case WM_MBUTTONUP:
        case WM_MOUSEWHEEL:
        case WM_MOUSEHWHEEL:
            break;
        }
        // 在窗口过程函数中修改INSERT键处理

        if (uMsg == WM_KEYDOWN && wParam == menu_kjj) {
            Menu::menu_open = !Menu::menu_open;
            CloseAllPopupWindows(); // 关闭所有弹出窗口
        }
        main::UpdateCursor();
        if (Menu::menu_open &&
            (uMsg == WM_LBUTTONDOWN ||
                uMsg == WM_RBUTTONDOWN ||
                uMsg == WM_MOUSEMOVE ||
                uMsg == WM_LBUTTONUP ||
                uMsg == WM_RBUTTONUP ||
                uMsg == WM_MOUSEWHEEL ||
                uMsg == WM_MOUSEHWHEEL)) {
            return true;
        }
    }
    else {
        switch (uMsg) {
        case WM_KEYDOWN:
        case WM_KEYUP:
            break;
        }
        if (uMsg == WM_KEYDOWN && wParam == menu_kjj) {
            Menu::menu_open = !Menu::menu_open;
        }
        main::UpdateCursor();
    }
    return CallWindowProc(origin_wndProc, hwnd, uMsg, wParam, lParam);
}

namespace main {
    static bool blastMenuOpen = false;
    ICVarSystem* CVar = nullptr;

    void* GetInterface(std::string_view szModule, std::string_view szInterface) {
        HMODULE pModule = GetModuleHandleA(szModule.data());
        if (!pModule) return nullptr;

        FARPROC pCreateIfc = GetProcAddress(pModule, "CreateInterface");
        if (!pCreateIfc) return nullptr;

        return reinterpret_cast<void* (*)(const char*, int*)>(pCreateIfc)(szInterface.data(), nullptr);
    }

    void* GetExport(std::string_view szModule, std::string_view szExport) {
        HMODULE pModule = GetModuleHandleA(szModule.data());
        if (!pModule) return nullptr;
        return GetProcAddress(pModule, szExport.data());
    }

    // 更新鼠标光标状态的函数
    void UpdateCursor() {
        // 静态变量：获取游戏输入系统接口（只在第一次调用时初始化）
        static void* pInputSystem = GetInterface("inputsystem.dll", "InputSystemVersion001");
        // 静态变量：获取SDL库中的函数指针（只在第一次调用时初始化）
        static auto SDL_SetWindowMouseGrab = (int(*)(void*, int))GetExport("sdl3.dll", "SDL_SetWindowMouseGrab");  // 设置窗口鼠标捕获状态(1捕获/0释放)
        static auto SDL_WarpMouseInWindow = (int(*)(void*, float, float))GetExport("sdl3.dll", "SDL_WarpMouseInWindow");  // 将鼠标移动到窗口指定坐标
        static auto SDL_GetWindowRelativeMouseMode = (bool(*)(void*))GetExport("sdl3.dll", "SDL_GetWindowRelativeMouseMode");  // 获取鼠标相对模式状态
        static auto SDL_SetWindowRelativeMouseMode = (void(*)(void*, bool))GetExport("sdl3.dll", "SDL_SetWindowRelativeMouseMode");  // 设置鼠标相对模式(用于FPS视角控制)
        // 从输入系统接口中获取窗口指针（通过固定偏移量0x2648）
        void* window = *(void**)((uintptr_t)pInputSystem + 0x2648);
        if (blastMenuOpen != Menu::menu_open) {
            blastMenuOpen = Menu::menu_open;
            if (!SDL_GetWindowRelativeMouseMode(window)) {
                SDL_SetWindowRelativeMouseMode(window, !Menu::menu_open);
                SDL_SetWindowMouseGrab(window, Menu::menu_open);
            }
            if (SDL_GetWindowRelativeMouseMode(window)) {
                ImVec2 size = ImGui::GetIO().DisplaySize;
                SDL_SetWindowMouseGrab(window, !Menu::menu_open);
                SDL_WarpMouseInWindow(nullptr, size.x / 2.f, size.y / 2.f);
                SDL_SetWindowRelativeMouseMode(window, true);
            }
        }
        if (Menu::menu_open && SDL_GetWindowRelativeMouseMode(window)) {
            SDL_SetWindowRelativeMouseMode(window, false);
        }
    }
}

// 安全的MinHook安装函数
bool InstallHook(void* target, void* detour, void** original) {
    EnterCriticalSection(&g_hookCriticalSection);

    MH_STATUS status = MH_CreateHook(target, detour, original);
    if (status == MH_OK) {
        status = MH_EnableHook(target);
        if (status == MH_OK) {
            g_hookedFunctions.insert(target);
            LeaveCriticalSection(&g_hookCriticalSection);
            return true;
        }
    }

    LeaveCriticalSection(&g_hookCriticalSection);
    return false;
}

void TrackResource(void* resource, const std::string& type, const std::string& description) {
    EnterCriticalSection(&g_resourceCriticalSection);
    g_trackedResources.push_back({ resource, type, description });
    LeaveCriticalSection(&g_resourceCriticalSection);
}

void ReleaseTrackedResources(const std::string& type) {
    EnterCriticalSection(&g_resourceCriticalSection);
    for (auto it = g_trackedResources.begin(); it != g_trackedResources.end(); ) {
        if (it->type == type && it->resource) {
            if (type == "ID3D11ShaderResourceView") {
                ((ID3D11ShaderResourceView*)it->resource)->Release();
            }
            else if (type == "ID3D11RenderTargetView") {
                ((ID3D11RenderTargetView*)it->resource)->Release();
            }
            else if (type == "ID3D11DeviceContext") {
                ((ID3D11DeviceContext*)it->resource)->Release();
            }
            else if (type == "ID3D11Device") {
                ((ID3D11Device*)it->resource)->Release();
            }
            else if (type == "IDXGISwapChain") {
                ((IDXGISwapChain*)it->resource)->Release();
            }
            it = g_trackedResources.erase(it);
        }
        else {
            ++it;
        }
    }
    LeaveCriticalSection(&g_resourceCriticalSection);
}

DWORD WINAPI VSThread(LPVOID lpParam) {
    vs::Run();
    return 0;
}

DWORD WINAPI Target_Bot(LPVOID lpParam) {
    target_bot_Run();
    return 0;
}


DWORD WINAPI Aim_Bot(LPVOID lpParam) {
    Aim_bot_Run();
    return 0;
}


BOOL InitializeModule(HMODULE hModule) {
    // 初始化临界区
    InitializeCriticalSection(&g_hookCriticalSection);
    InitializeCriticalSection(&g_resourceCriticalSection);

    if (MH_Initialize() != MH_OK) {
        return FALSE;
    }

    g_hThisDll = hModule;

    g_hMainThread = CreateThread(NULL, 0, create, NULL, 0, NULL);
    if (!g_hMainThread) {
        return FALSE;
    }
    g_dataThreadRunning = true;
    g_hDataThread = CreateThread(NULL, 0, DataUpdateThread, NULL, 0, NULL);
    g_hookThreadRunning = true;
    g_hHookThread = CreateThread(NULL, 0, HookThread, NULL, 0, NULL);
    g_aimbothookThreadRunning = true;
    g_haimbotHookThread = CreateThread(NULL, 0, aimbotHookThread, NULL, 0, NULL);
    CreateThread(NULL, 0, VSThread, NULL, 0, NULL);
    CreateThread(NULL, 0, Target_Bot, NULL, 0, NULL);
    CreateThread(NULL, 0, Aim_Bot, NULL, 0, NULL);

    MenuAnimationManager::ResetAnimation(Menu::menu_open);
    g_moduleInitialized = true;
    return TRUE;
}

void ShutdownModule() {
    g_shutdownRequested = true;

    g_dataThreadRunning = false;
    if (g_hDataThread) {
        DWORD waitResult = WaitForSingleObject(g_hDataThread, 2000);
        if (waitResult == WAIT_OBJECT_0) {
            CloseHandle(g_hDataThread);
            g_hDataThread = nullptr;
        }
        else {
            TerminateThread(g_hDataThread, 0);
            CloseHandle(g_hDataThread);
            g_hDataThread = nullptr;
        }
    }

    g_hookThreadRunning = false;
    if (g_hHookThread) {
        DWORD waitResult = WaitForSingleObject(g_hHookThread, 2000);
        if (waitResult == WAIT_OBJECT_0) {
            CloseHandle(g_hHookThread);
            g_hHookThread = nullptr;
        }
        else {
            TerminateThread(g_hHookThread, 0);
            CloseHandle(g_hHookThread);
            g_hHookThread = nullptr;
        }
    }
    g_aimbothookThreadRunning = false;
    if (g_haimbotHookThread) {
        DWORD waitResult = WaitForSingleObject(g_haimbotHookThread, 2000);
        if (waitResult == WAIT_OBJECT_0) {
            CloseHandle(g_haimbotHookThread);
            g_haimbotHookThread = nullptr;
        }
        else {
            TerminateThread(g_haimbotHookThread, 0);
            CloseHandle(g_haimbotHookThread);
            g_haimbotHookThread = nullptr;
        }
    }
    // 确保主线程也被清理
    if (g_hMainThread) {
        WaitForSingleObject(g_hMainThread, 1000);
        CloseHandle(g_hMainThread);
        g_hMainThread = nullptr;
    }

    // 清理MinHook
    EnterCriticalSection(&g_hookCriticalSection);
    for (void* hook : g_hookedFunctions) {
        MH_DisableHook(hook);
        MH_RemoveHook(hook);
    }
    g_hookedFunctions.clear();
    MH_Uninitialize();
    LeaveCriticalSection(&g_hookCriticalSection);

    // 释放所有跟踪的资源
    ReleaseTrackedResources("ID3D11ShaderResourceView");
    ReleaseTrackedResources("ID3D11RenderTargetView");
    ReleaseTrackedResources("ID3D11DeviceContext");
    ReleaseTrackedResources("ID3D11Device");
    ReleaseTrackedResources("IDXGISwapChain");

    // 删除临界区
    DeleteCriticalSection(&g_hookCriticalSection);
    DeleteCriticalSection(&g_resourceCriticalSection);

    g_moduleInitialized = false;
}

// 在全局变量区添加
static bool g_showInjectionAnimation = true;
static float g_injectionAnimAlpha = 1.0f;
static std::chrono::steady_clock::time_point g_animStartTime;
static std::vector<std::string> g_logoText = { "S", "H", "E", "N", "Y", "U", "A", "N" };
static size_t g_currentCharIndex = 0;
static float g_charDisplayTimer = 0.0f;

// Present Hook函数 - 移除了原本的功能函数调用
long __stdcall my_present(IDXGISwapChain* _this, UINT a, UINT b) {
    static bool texturesLoaded = false;
    static bool inited = false;

    if (!inited) {
        _this->GetDevice(__uuidof(ID3D11Device), (void**)&g_pd3dDevice);
        g_pd3dDevice->GetImmediateContext(&g_pd3dContext);

        DXGI_SWAP_CHAIN_DESC sd;
        _this->GetDesc(&sd);
        g_hwnd = sd.OutputWindow;

        ID3D11Texture2D* buf{};
        _this->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&buf);

        g_pd3dDevice->CreateRenderTargetView(buf, nullptr, &view);
        TrackResource(view, "ID3D11RenderTargetView", "Main Render Target");

        buf->Release();

        origin_wndProc = (WNDPROC)SetWindowLongPtr(g_hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc);

        ImGui::CreateContext();
        ImGuiIO& io = ImGui::GetIO(); (void)io;
        io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;

        auto draw = ImGui::GetBackgroundDrawList();
        ImFontConfig font_cfg;
        font_cfg.FontDataOwnedByAtlas = false;
        ImFont* font = io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\msyhbd.ttc", 25.0f, &font_cfg, io.Fonts->GetGlyphRangesChineseFull());
        ImGui_ImplWin32_Init(g_hwnd);
        ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dContext);
        TrackResource(g_pd3dDevice, "ID3D11Device", "Main D3D11 Device");
        TrackResource(g_pd3dContext, "ID3D11DeviceContext", "Main D3D11 Device Context");

        if (!texturesLoaded) {
            LoadAllTextures();
            texturesLoaded = true;
        }
        g_animStartTime = std::chrono::steady_clock::now();
        inited = true;
    }

    RECT Rect{};
    GetClientRect(g_hwnd, &Rect);
    m_size = ImVec2((float)Rect.right, (float)Rect.bottom);

    ImGui_ImplDX11_NewFrame();
    ImGui_ImplWin32_NewFrame();
    ImGui::NewFrame();
    CheckKeySelection();

    MenuAnimationManager::UpdateAnimation(Menu::menu_open, ImGui::GetIO().DeltaTime);
    float alphaAnim = MenuAnimationManager::GetAlpha();

    MessageWindow::Render();

    if (g_showInjectionAnimation) {
        auto currentTime = std::chrono::steady_clock::now();
        auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - g_animStartTime).count();

        // 绘制半透明背景
        ImDrawList* draw = ImGui::GetBackgroundDrawList();
        draw->AddRectFilled(ImVec2(0, 0), m_size, IM_COL32(0, 0, 0, 220 * g_injectionAnimAlpha), 0);

        // 计算中心位置
        ImVec2 center = ImVec2(m_size.x * 0.5f, m_size.y * 0.5f);
        const float charSpacing = 30.0f;
        const float fontSize = 150.0f;
        const float verticalOffset = -20.0f;
        // 创建临时窗口用于文字渲染
        ImGui::SetNextWindowPos(ImVec2(0, 0));
        ImGui::SetNextWindowSize(m_size);
        ImGui::Begin("##LogoAnimationWindow", nullptr,
            ImGuiWindowFlags_NoTitleBar |
            ImGuiWindowFlags_NoResize |
            ImGuiWindowFlags_NoScrollbar |
            ImGuiWindowFlags_NoBackground |
            ImGuiWindowFlags_NoInputs);

        // 设置字体大小
        ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[0]);
        ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(charSpacing, 0));
        ImGui::SetWindowFontScale(6.f);


        // 计算起始位置（整体居中）
        float totalContentWidth = 0.0f;
        for (size_t i = 0; i < g_logoText.size(); ++i) {
            totalContentWidth += ImGui::CalcTextSize(g_logoText[i].c_str()).x;
            if (i < g_logoText.size() - 1) {
                totalContentWidth += charSpacing;
            }
        }

        // 设置起始位置（精确居中）
        ImGui::SetCursorPosX(center.x - totalContentWidth * 0.5f);
        ImGui::SetCursorPosY(center.y - fontSize * 0.5f + verticalOffset);

        // 检查所有文字是否都已加载
        bool allTextLoaded = (elapsed >= (g_logoText.size() * 400 + 600)); // 所有文字显示完成 + 1秒缓冲

        // 记录所有文字加载完成的时间
        static std::chrono::steady_clock::time_point allTextLoadedTime;
        static bool allTextLoadedRecorded = false;


        if (allTextLoaded && !allTextLoadedRecorded) {
            allTextLoadedTime = currentTime;
            allTextLoadedRecorded = true;
        }

        for (size_t i = 0; i < g_logoText.size(); ++i) {
            // 计算当前字母的开始时间（每个字母延迟200毫秒出现）
            long long charStartTime = i * 400; // 每个字母延迟200毫秒

            // 修改：将淡入时间延长到1000毫秒（1秒）
            float charProgress = std::clamp(static_cast<float>(elapsed - charStartTime) / 600.0f, 0.0f, 1.0f);

            // 应用全局动画透明度
            float charAlpha = charProgress * g_injectionAnimAlpha;

            // 只有当字母有透明度时才绘制
            if (charAlpha > 0.01f) {
                ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, charAlpha), "%s", g_logoText[i].c_str());
                if (i < g_logoText.size() - 1) {
                    ImGui::SameLine();
                }
            }
        }

        ImGui::SetWindowFontScale(1.f);
        ImGui::PopStyleVar();
        ImGui::PopFont();
        ImGui::End();

        // 动画淡出逻辑 - 在所有文字加载后1秒开始
        if (allTextLoaded) {
            auto timeSinceAllLoaded = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - allTextLoadedTime).count();

            if (timeSinceAllLoaded > 900) { // 所有文字加载后等待1秒
                g_injectionAnimAlpha -= 0.008f;
                if (g_injectionAnimAlpha <= 0.0f) {
                    g_showInjectionAnimation = false;
                    // 重置状态以便下次使用
                    allTextLoadedRecorded = false;
                }
            }
        }
    }
    // 只有动画结束后才绘制其他UI
    if (!g_showInjectionAnimation) {
        if (alphaAnim > 0.0f || Menu::menu_open) {
            Menu::Screenui();
        }

        if (all_settings::visual::ESP) {
            drawEsp();
            if (all_settings::visual::local::self::show_crosshair) {
                drawcrosshair();
            }
            if (all_settings::visual::local::world::draw_C4_time)
            {
                draw_C4();
            }
        }
        if (all_settings::visual::local::world::draw_fov) {
            if (all_settings::aimbot_anitaimbot::aimbot::open_aimbot.enabled)
            {
                drawfov();
            }
        }


        // 保存成功提示逻辑保持不变
        if (showSaveSuccess) {
            auto now = std::chrono::steady_clock::now();
            auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - saveSuccessTime).count();

            if (elapsed > 1500) {
                saveSuccessAlpha -= 0.01f;
                if (saveSuccessAlpha <= 0.0f) {
                    saveSuccessAlpha = 0.0f;
                    showSaveSuccess = false;
                }
            }

            ImGui::SetNextWindowBgAlpha(saveSuccessAlpha);
            ImGui::SetNextWindowPos(ImVec2(ImGui::GetIO().DisplaySize.x - 20, 50),
                ImGuiCond_Always, ImVec2(1.0f, 0.0f));

            if (ImGui::Begin("SaveSuccess", nullptr,
                ImGuiWindowFlags_NoDecoration |
                ImGuiWindowFlags_AlwaysAutoResize |
                ImGuiWindowFlags_NoSavedSettings |
                ImGuiWindowFlags_NoFocusOnAppearing |
                ImGuiWindowFlags_NoNav)) {
                ImGui::TextColored(ImVec4(0.0f, 1.0f, 0.0f, saveSuccessAlpha), u8"配置保存成功");
            }
            ImGui::End();
        }
    }

    ImGui::EndFrame();
    ImGui::Render();
    g_pd3dContext->OMSetRenderTargets(1, &view, nullptr);
    ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
    return ((Present)origin_present)(_this, a, b);
}

// 数据获取线程函数 - 保持不变
DWORD WINAPI DataUpdateThread(LPVOID lpParam) {
    auto& playerManager = PlayerDataManager::GetInstance();
    playerManager.StartUpdateThread();
    while (g_dataThreadRunning) {
        //autostop_fire();
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    playerManager.StopUpdateThread();
    return 0;
}

static void* CreateInterface(const char* moduleName, const char* interfaceName) {
    HMODULE hModule = GetModuleHandleA(moduleName);
    if (!hModule) return nullptr;

    auto pFunc = reinterpret_cast<void* (*)(const char*, int*)>(GetProcAddress(hModule, "CreateInterface"));
    if (!pFunc) return nullptr;

    return pFunc(interfaceName, nullptr);
}


DWORD create(void*) {
    const unsigned level_count = 2;
    D3D_FEATURE_LEVEL levels[level_count] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0 };
    DXGI_SWAP_CHAIN_DESC sd{};
    sd.BufferCount = 1;
    sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.OutputWindow = GetForegroundWindow();
    sd.SampleDesc.Count = 1;
    sd.Windowed = true;
    sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

    auto hr = D3D11CreateDeviceAndSwapChain(
        nullptr,
        D3D_DRIVER_TYPE_HARDWARE,
        nullptr,
        0,
        levels,
        level_count,
        D3D11_SDK_VERSION,
        &sd,
        &g_pSwapChain,
        &g_pd3dDevice,
        nullptr,
        nullptr);

    if (g_pSwapChain) {
        auto vtable_ptr = (void***)(g_pSwapChain);
        auto vtable = *vtable_ptr;
        auto present = vtable[8];

        // 使用安全的InstallHook函数
        if (!InstallHook(present, my_present, &origin_present)) {
        }

        TrackResource(g_pd3dDevice, "ID3D11Device", "Main D3D11 Device");
        TrackResource(g_pSwapChain, "IDXGISwapChain", "Main Swap Chain");

        g_pd3dDevice->Release();
        g_pSwapChain->Release();
    }

    // 创建控制台
    AllocConsole();
    FILE* file;
    freopen_s(&file, "CONOUT$", "w", stdout);

    engine_client = (EngineClient*)CreateInterface("engine2.dll", "Source2EngineToClient001");

    // 首次调用时扫描CFG文件
    static bool firstRun = true;
    if (firstRun) {
        scanCfgFiles();
        firstRun = false;
    }

    return 0;
}

// SetUp函数 - 保持不变
void SetUp() {
    client.dll = (uintptr_t)GetModuleHandleA("client.dll");
    IBeamTracerListener::Setup();
}

// 安全卸载线程函数
DWORD WINAPI SafeUnloadThread(LPVOID lpParam) {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));

    ShutdownModule();

    FreeLibraryAndExitThread(g_hThisDll, 0);
    return 0;
}

// ==================== DllMain函数 ====================
static BOOL __stdcall DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
    switch (ul_reason_for_call) {
    case DLL_PROCESS_ATTACH: {
        DisableThreadLibraryCalls(hModule);

        // 使用模块化初始化
        if (!InitializeModule(hModule)) {
            return FALSE;
        }
        break;
    }

    case DLL_PROCESS_DETACH: {
        // 只有在正常卸载时执行清理（lpReserved == nullptr）
        if (lpReserved == nullptr && g_moduleInitialized) {
            // 创建安全卸载线程
            g_hUnloadThread = CreateThread(NULL, 0, SafeUnloadThread, NULL, 0, NULL);
            if (g_hUnloadThread) {
                WaitForSingleObject(g_hUnloadThread, 3000);
                CloseHandle(g_hUnloadThread);
                g_hUnloadThread = nullptr;
            }
        }
        break;
    }

    case DLL_THREAD_DETACH:
    case DLL_THREAD_ATTACH:
        break;
    }
    return TRUE;
}